<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2020/10/12
 * Time: 4:06 PM
 */
namespace app\index\logic;

use app\model\Token;
use app\model\User;
use app\model\Wx;
use app\service\WxService;
use think\facade\Request;

class AuthLogic
{

    public function check()
    {

        $token = Request::header('token') ? Request::header('token') : Request::param('token');

        if(env('APP_ENV') == 'local'){
            $token = $token ?? 'bad35416f8efd36611e6549abdbf3d21';
        }
        if (!$token) {
            fail('请先登录系统',[],401);
        }

        $tokenModel = new Token();
        $uid = $tokenModel->verifyToken($token);

        $userModel = new User();
        $userInfo = $userModel->getUserDetailInfoById($uid,'user.*,org.id as orgid,isphoto,orgname');
        config($userInfo,'user');
        return true;
    }


    public function codeLogin($code)
    {

        $wxService = new WxService();

        $wxRet = $wxService->code2Session($code);
        if($wxRet){
            $wxModel = new Wx();
            //判断微信是否存在
            $wxInfo = $wxModel->getWxInfByOpenid($wxRet['openid'],'wx_openid as openid,wx_session_key as session_key');
            if($wxInfo){
                $update = [
                    'wx_session_key' => $wxRet['session_key']
                ];
                $wxModel->updateWxInfoByWhere(['wx_openid'=>$wxInfo['openid']],$update);
                $openid = $wxInfo['openid'];
            }else{
                //保存微信信息
                $wx = [
                    'wx_openid' => $wxRet['openid'],
                    'wx_session_key' => $wxRet['session_key'],
                ];
                $wxModel->addOneWx($wx);
                $openid = $wxRet['openid'];
            }
            return ['openid'=>$openid];
        }

        fail('微信登录失败，请稍后重试');
    }

}